package com.yokead.controller;

import cn.jiangzeyin.StringUtil;
import cn.jiangzeyin.common.JsonMessage;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yokead.common.Config;
import com.yokead.common.UserUtil;
import com.yokead.common.base.AdminBaseControl;
import com.yokead.common.interceptor.LoginInterceptor;
import com.yokead.common.interceptor.NotLogin;
import com.yokead.system.log.SystemLog;
import com.yokead.util.JsonUtil;
import org.springframework.context.annotation.Scope;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.WebApplicationContext;

import java.io.IOException;
import java.util.Iterator;

/**
 * Created by jiangzeyin on 2017/5/9.
 *
 * @author jiangzeyin
 */
@Controller
@Scope(WebApplicationContext.SCOPE_SESSION)
public class LoginControl extends AdminBaseControl {

    @RequestMapping(value = "login.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    @NotLogin
    public String login(String way) {
        //
        if (!StringUtil.isEmpty(way)) {
            getSession().invalidate();
        }
        return "login";
    }

    @RequestMapping(value = "checkPwd.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String checkPwd(String pwd) {
        if (UserUtil.isSystemManage(userName)) {
            return JsonMessage.getString(400, "系统管理员不能在此修改密码");
        }
        if (StringUtil.isEmpty(pwd, 4, 20)) {
            return JsonMessage.getString(400, "请输入4-20的位的密码");
        }
        try {
            boolean flag = UserUtil.login(userName, pwd);
            if (flag) {
                return JsonMessage.getString(200, "");
            }
            return JsonMessage.getString(405, "旧密码不正确");
        } catch (Exception e) {
            SystemLog.ERROR().error("验证密码失败", e);
            return JsonMessage.getString(500, "验证异常,请联系管理员");
        }
    }

    @RequestMapping(value = "changPwd.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String checkPwd(String pwd, String newPwd) throws IOException {
        try {
            boolean flag = UserUtil.login(userName, pwd);
            if (!flag) {
                return JsonMessage.getString(405, "旧密码不正确");
            }
        } catch (Exception e) {
            SystemLog.ERROR().error("验证密码失败", e);
            return JsonMessage.getString(500, "修改密码异常,请联系管理员");
        }
        if (StringUtil.isEmpty(newPwd, 4, 20)) {
            return JsonMessage.getString(400, "请输入4-20的位的密码");
        }
        String filePath = Config.Admin.getUserConfigFile();
        JSONArray jsonArray = (JSONArray) JsonUtil.readJson(filePath);
        Iterator<Object> iterable = jsonArray.iterator();
        boolean find = false;
        while (iterable.hasNext()) {
            JSONObject jsonObject = (JSONObject) iterable.next();
            String userName = jsonObject.getString("name");
            if (this.userName.equals(userName)) {
                jsonObject.put("pwd", newPwd);
                find = true;
                break;
            }
        }
        if (!find) {
            return JsonMessage.getString(500, "修改密码失败");
        }
        //String newsJson = JsonUtil.formatJson(jsonArray.toString());
        //FileUtil.writeFile(filePath, newsJson);
        JsonUtil.saveJson(filePath, jsonArray);
        return JsonMessage.getString(200, "");
    }

    /**
     * 登录方法
     *
     * @param name
     * @param pwd
     * @return
     */
    @RequestMapping(value = "login_to", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    @NotLogin
    public String login_ok(String name, String pwd) {
        StringBuilder stringBuffer = new StringBuilder();
        stringBuffer.append("用户登录：").append(name).append(",IP：").append(getIp());
        stringBuffer.append(",浏览器：").append(getUserAgent());
        try {
            boolean flag = UserUtil.login(name, pwd);
            if (flag) {
                stringBuffer.append("，结果：").append("OK");
                setSessionAttribute(LoginInterceptor.SESSION_NAME, name);
                return JsonMessage.getString(200, "登录成功");
            } else {
                stringBuffer.append("，结果：").append("faild");
            }
            return JsonMessage.getString(400, "登录失败，请输入正确的密码和账号");
        } catch (Exception e) {
            stringBuffer.append("，结果：").append("error");
            SystemLog.ERROR().error("登录异常", e);
            return JsonMessage.getString(500, "登录异常：" + e.getLocalizedMessage());
        } finally {
            SystemLog.LOG().info(stringBuffer.toString());
        }
    }
}
